<template>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px" class="demo-ruleForm">
        <el-form-item label="赛事名称" prop="name">
            <el-input v-model="ruleForm.name" placeholder="赛事名称"></el-input>
        </el-form-item>
        <el-form-item label="赛事项目" prop="gameItem">
            <el-input v-model="ruleForm.gameItem" placeholder="赛事项目"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
            <el-input v-model="ruleForm.price" placeholder="价格"></el-input>
        </el-form-item>
        <el-form-item label="报名时间" prop="startRegistrationTime">
            <el-date-picker v-model="ruleForm.startRegistrationTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"
                placeholder="选择日期">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="报名截止" prop="endRegistrationTime">
            <el-date-picker v-model="ruleForm.endRegistrationTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"
                placeholder="选择日期">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="比赛时间" prop="gameTime">
            <el-date-picker v-model="ruleForm.gameTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="比赛截止" prop="gameEndTime">
            <el-date-picker v-model="ruleForm.gameEndTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="比赛地点" prop="gameSite">
            <el-input v-model="ruleForm.gameSite"></el-input>
        </el-form-item>
        <el-form-item label="赛事缩略图" prop="gamePicUrl">
            <el-upload class="avatar-uploader" :action="url" :show-file-list="false" :on-success="upSuccess"
                :headers="{ token: token }">
                <img v-if="ruleForm.gamePicUrl" :src="ruleForm.gamePicUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <el-input v-model="ruleForm.gamePicUrl" style="display: none"></el-input>
        </el-form-item>
        <el-form-item label="赛事介绍" prop="gameContent" style="width: 100%;" class="edit-parent">

            <div class="editBox">
                <quill-editor class="editor" v-model="ruleForm.gameContent" :options="editorOption"></quill-editor>
            </div>
        </el-form-item>

        <el-form-item>
            <div class="footer-box">
                <el-button @click="cancle">取 消</el-button>
                <el-button type="primary" @click="submitForm('ruleForm')">{{ $route.query.id ? '更新' : '立即创建' }}</el-button>
            </div>
        </el-form-item>
    </el-form>
</template>
<script>
import { Quill } from 'vue-quill-editor'
import quillEmoji from 'quill-emoji'
import 'quill-emoji/dist/quill-emoji.css'
Quill.register('modules/quillEmoji', quillEmoji)
import { uploadFile } from "@/config/interface";
import { gameSave, gameShow } from '@/config/api'
import { times, divide } from '@/utils/tools';
import { container, ImageExtend, QuillWatch } from 'quill-image-extend-module'
Quill.register('modules/ImageExtend', ImageExtend)

export default {

    data() {
        return {
            editorOption: {
                // some quill options
                modules: {
                    ImageExtend: {
                        loading: true,
                        name: "file",
                        size: 0.02,
                        action: "http://192.168.1.251/apiBs/util/uploadFile",
                        response: res => {
                            console.log(res)
                            return res.result;
                        },
                        headers: (xhr, formData) => {
                            xhr.setRequestHeader(
                             "token",
                             this.$store.state.login.token
                            );
                        }, // 可选参数 设置请求头部
                        sizeError: () => {
                            return this.$message.error("图片超过50kb");
                        } // 图片超过大小的回调
                    },
                    toolbar: {
                        container: [
                            ["bold", "italic", "underline", "strike"],
                            ["blockquote", "code-block"],
                            [{ header: 1 }, { header: 2 }],
                            [{ list: "ordered" }, { list: "bullet" }],
                            [{ script: "sub" }, { script: "super" }],
                            [{ indent: "-1" }, { indent: "+1" }],
                            [{ direction: "rtl" }],
                            [{ size: ["small", false, "large", "huge"] }],
                            [{ header: [1, 2, 3, 4, 5, 6, false] }],
                            [{ color: [] }, { background: [] }],
                            [{ font: [] }],
                            [{ align: [] }],
                            ["clean"],
                            ["link", "image", "video"],

                        ],
                        handlers: {
                            image: function () {
                                QuillWatch.emit(this.quill.id);
                            }
                        }
                    }
                },
                placeholder: "请填写内容"
            },
            url: "",
            token: "",


            ruleForm: {
                name: "",
                gameItem: "",
                price: "",
                startRegistrationTime: "",
                endRegistrationTime: "",
                gameTime: "",
                gameEndTime: "",
                gameSite: "",
                gamePicUrl: "",
                gameContent: ""
            },
            rules: {
                name: [
                    { required: true, message: '请输入赛事名称', trigger: 'blur' },
                ],
                gameItem: [
                    { required: true, message: '请输入赛事项目', trigger: 'blur' },
                ],
                price: [
                    { required: true, message: '请输入赛事价格', trigger: 'blur' },
                ],
                startRegistrationTime: [
                    { required: true, message: '请选择报名时间', trigger: 'change' },
                ],
                endRegistrationTime: [
                    { required: true, message: '请选择报名截止时间', trigger: 'change' },
                ],
                gameTime: [
                    { required: true, message: '请选择比赛时间', trigger: 'change' },
                ],
                gameEndTime: [
                    { required: true, message: '请选择比赛截止时间', trigger: 'change' },
                ],
                gameSite: [
                    { required: true, message: '请输入比赛地点', trigger: 'blur' },
                ],
                gamePicUrl: [
                    { required: true, message: '请选择赛事缩略图', trigger: 'change' },
                ],
                gameContent: [
                    { required: true, message: '请输入赛事介绍', trigger: 'blur' },
                ]
            }
        };
    },
    created() {
        this.url = uploadFile()
        this.token = this.$store.state.login.token;
        if (this.$route.query.id) {
            this.getGameInfo(this.$route.query.id)
        }

    },
    methods: {
        // 获取赛事详情
        async getGameInfo(id) {
            const res = await gameShow({ id })
            this.ruleForm = {
                name: res.data.result.name,
                gameItem: res.data.result.gameItem,
                price: divide(res.data.result.price, 100),
                startRegistrationTime: res.data.result.startRegistrationTime,
                endRegistrationTime: res.data.result.endRegistrationTime,
                gameTime: res.data.result.gameTime,
                gameEndTime: res.data.result.gameEndTime,
                gameSite: res.data.result.gameSite,
                gamePicUrl: res.data.result.gamePicUrl,
                gameContent: res.data.result.gameContent,
                id: res.data.result.id
            }
        },

        async show() {
            this.dialogVisible = true
            const result = await gameTemplatePageList({ page: 1, pageSize: 100 })
            this.tableList = result.data.result.list
        },
        onCreated(editor) {
            this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
        },
        // 取消
        cancle(e) {
            this.$router.go(-1)
        },
        // 创建赛事
        submitForm(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    const startRegistrationTime = new Date(this.ruleForm.startRegistrationTime).getTime()
                    const endRegistrationTime = new Date(this.ruleForm.endRegistrationTime).getTime()
                    const gameTime = new Date(this.ruleForm.gameTime).getTime()
                    const gameEndTime = new Date(this.ruleForm.gameEndTime).getTime()
                    if (endRegistrationTime <= startRegistrationTime) {
                        this.$alert('报名截止时间不能小于报名时间', '提示', {
                            confirmButtonText: '确定',
                        });
                        return false
                    }
                    if (gameEndTime <= gameTime) {
                        this.$alert('比赛截止时间不能小于比赛时间', '提示', {
                            confirmButtonText: '确定',
                        });
                        return false
                    }
                    if (gameTime <= endRegistrationTime) {
                        this.$alert('比赛日期不能小于报名截止时间', '提示', {
                            confirmButtonText: '确定',
                        });
                        return false
                    }
                    this.ruleForm.price = times(this.ruleForm.price, 100)
                    const res = await gameSave(this.ruleForm)
                    if (res.data.status == 200) {
                        this.$alert('操作成功', '提示', {
                            confirmButtonText: '确定',
                            callback: action => {
                                this.$router.go(-1)
                            }
                        });
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        // 上传图片
        upSuccess(file) {
            this.ruleForm.gamePicUrl = file.result
        },




    }
};
</script>
<style scoped>
.footer-box {
    display: flex;
    justify-content: center;
    width: 1200px;

}

.demo-ruleForm {
    display: flex;
    flex-wrap: wrap;
    margin-right: 140px;
    height: calc(100vh - 100px);
    overflow-y: scroll;
}

.demo-ruleForm::-webkit-scrollbar {
    width: 0;
}
</style>

<style>
.editBox {
    width: 1200px;
    background: #fff;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    background: #fff;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>